package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.*;
import com.itheima.health.service.MemberService;
import com.itheima.health.service.OrderService;
import com.itheima.health.service.OrderSettingService;
import com.itheima.health.service.SetmealService;
import com.itheima.health.utils.DateUtils;
import com.itheima.health.utils.SMSUtils;
import com.lowagie.text.*;
import com.lowagie.text.Font;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 提交体检预约审核功能
 *
 * @author zhengjd
 * @date 2020/4/8 10:26
 */
@RestController
@RequestMapping("/order")
public class OrderMobileController {

    @Autowired
    private JedisPool jedisPool;

    @Reference
    OrderSettingService orderSettingService;

    @Reference
    MemberService memberService;

    @Reference
    OrderService orderService;

    @Reference
    SetmealService setmealService;

    /**
     * 提交预约功能的审核实现
     *
     * @param map
     * @return
     */
    @RequestMapping("/submit")
    public Result submit(@RequestBody Map map) {
        String orderDate = (String) map.get("orderDate");  //预约日期
        String telephone = (String) map.get("telephone");  //手机号
        String validateCode = (String) map.get("validateCode"); //验证码
        String idCard = (String) map.get("idCard"); //身份证
        String name = map.get("name").toString();  //姓名
        String sex = map.get("sex").toString();  //性别
        String setmealId = (String) map.get("setmealId");
        Jedis jedis = null;
        try {
            //1.验证用户输入的验证码是否与Redis中缓存一致
            jedis = jedisPool.getResource();
            String redisCode = jedis.get(telephone + RedisMessageConstant.SENDTYPE_ORDER);
            if (!validateCode.equals(redisCode)) {
                //验证码不一致
                return new Result(false, MessageConstant.VALIDATECODE_ERROR);
            }
            //2.查询预约日期是否存在
            Boolean isExit = orderSettingService.QueryByOrderDate(orderDate);
            if (!isExit) {
                //预约日期不存在
                return new Result(false, MessageConstant.SELECTED_DATE_CANNOT_ORDER);
            }
            //3.查询指定日期是否约满
            Boolean isFull = orderSettingService.lessNumber2Reservations(orderDate);
            if (isFull) {
                //已约满
                return new Result(false, MessageConstant.ORDER_FULL);
            }

            //4.查询用户是否为会员(不是则自动注册为会员)
            Member member = memberService.findByTelephone(telephone);
            if (member == null) {
                member = new Member();
                member.setIdCard(idCard);
                member.setPhoneNumber(telephone);
                member.setName(name);
                member.setSex(sex);
                member.setRegTime(new Date());
                memberService.add(member);
            }
            //5.是否已经预约
            if (member != null) {
                //同一个人，同一套餐，同一时间
                Order order = new Order();
                order.setMemberId(member.getId());
                order.setOrderDate(DateUtils.parseString2Date(orderDate));
                order.setSetmealId(Integer.parseInt(setmealId));
                Boolean isOrder = orderService.findByCondition(order);
                if (isOrder) {
                    return new Result(false, MessageConstant.HAS_ORDERED);
                }
            }

            //6.往t_order表中添加预约数据
            Result result = orderService.add(map, member.getId());

            //7.更新t_ordersetting表的已预约人数+1
            orderSettingService.updateReservations(orderDate);
            SMSUtils.sendShortMessage(SMSUtils.ORDER_NOTICE, telephone, orderDate);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.ORDER_FAIL);
        } finally {
            if (jedis != null) {
                jedis.close();
            }
        }

    }

    /**
     * 根据id查询预约信息
     *
     * @param id
     * @return
     */
    @RequestMapping("/findById")
    public Result findById(Integer id) {
        try {
            Map map = orderService.findById(id);
            return new Result(true, MessageConstant.QUERY_ORDER_SUCCESS, map);
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.QUERY_ORDER_FAIL);
        }

    }

    /**
     * 将预约成功信息转换为pdf导出功能
     *
     * @param id
     * @return
     */
    @RequestMapping("/exportSetmealInfo")
    public Result exportSetmealInfo(Integer id, HttpServletRequest request, HttpServletResponse response) {
        try {
            //获取预约成功信息
            Map map = orderService.findById(id);
            //获取setmeal对象
            Setmeal setmeal = setmealService.findById((Integer) map.get("setmealId"));
            //设置头信息，以附件的形式导出
            response.setContentType("application/pdf");
            String filename = "exportPDF.pdf";
            response.setHeader("Content-Disposition",
                    "attachment;filename=" + filename);

            //生成PDF文件
            Document document = new Document();
            PdfWriter.getInstance(document, response.getOutputStream());
            document.open();
            //设置表格字体
            BaseFont baseFont = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false);
            Font font = new Font(baseFont, 10, Font.NORMAL, Color.BLUE);

            //写PDF数据，输出订单和套餐信息
            //体检人
            document.add(new Paragraph("体检人:" + map.get("member"), font));
            //体检套餐
            document.add(new Paragraph("体检套餐:" + map.get("setmeal"), font));
            //体检日期
            document.add(new Paragraph("体检日期:" + map.get("orderDate"), font));
            //预约类型
            document.add(new Paragraph("预约类型:" + map.get("orderType"), font));

            //创建pdf表格
            Table table = new Table(3);
            table.setWidth(80); // 宽度
            table.setBorder(1); // 边框
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); //水平对齐方式
            table.getDefaultCell().setVerticalAlignment(Element.ALIGN_TOP); // 垂直对齐方式
            /*设置表格属性*/
            table.setBorderColor(new Color(0, 0, 255)); //将边框的颜色设置为蓝色
            table.setPadding(5);//设置表格与字体间的间距
            //table.setSpacing(5);//设置表格上下的间距
            table.setAlignment(Element.ALIGN_CENTER);//设置字体显示居中样式
            //写表头
            table.addCell(buildCell("项目名称", font));
            table.addCell(buildCell("项目内容", font));
            table.addCell(buildCell("项目解读", font));
            //写数据（检查组和检查项）
            List<CheckGroup> checkGroups = setmeal.getCheckGroups();
            if (checkGroups != null && checkGroups.size() > 0) {
                for (CheckGroup checkGroup : checkGroups) {
                    table.addCell(buildCell(checkGroup.getName(), font));
                    //拼接检查项
                    StringBuffer checkItems = new StringBuffer();
                    List<CheckItem> checkItemList = checkGroup.getCheckItems();
                    if (checkItemList != null && checkItemList.size() > 0) {
                        for (CheckItem checkItem : checkItemList) {
                            checkItems.append(checkItem.getName() + "  ");
                        }
                        table.addCell(buildCell(checkItems.toString(), font));
                        table.addCell(buildCell(checkGroup.getRemark(), font));
                    }
                }
            }
            //将表格添加到pdf中
            document.add(table);
            document.close();
            return null;
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false, MessageConstant.EXPORT_ORDERSUCCESS_FAIL);
        }

    }

    // 传递内容和字体样式，生成单元格
    private Cell buildCell(String content, Font font)
            throws BadElementException {
        Phrase phrase = new Phrase(content, font);
        return new Cell(phrase);
    }


}
